<template>
  <BasePage>
    <MyTable
      ref="$table"
      :columns="columns"
      :query-schemas="querySchemas"
      :get-data="deptApi.list"
      default-expand-all
    >
      <template #handle>
        <AddButton v-auth="`dept_manage_add`" @click="fromAdd()">添加部门</AddButton>
      </template>
    </MyTable>
    <MyForm ref="$form" :model-form="model" @submit="handleSubmit">
      <n-form-item label="上级部门" path="parentId">
        <n-cascader
          v-model:value="model.parentId"
          :options="parentOptions"
          clearable
          filterable
          value-field="id"
          :disabled="type !== 'add'"
        />
      </n-form-item>
      <n-form-item
        label="部门名称"
        path="name"
        :rule="{ required: true, message: '请输入部门名称' }"
      >
        <n-input v-model:value="model.name" maxlength="20" clearable show-count />
      </n-form-item>
      <n-form-item label="备注" path="remark">
        <n-input
          v-model:value="model.remark"
          type="textarea"
          maxlength="100"
          clearable
          show-count
          :autosize="{
            minRows: 3,
          }"
        />
      </n-form-item>
    </MyForm>
  </BasePage>
</template>
<script setup lang="jsx">
defineOptions({ name: 'DeptManage' })
import * as deptApi from '@/api/dept'
import { useCrud } from '@/hooks/useCrud'
const querySchemas = []
const columns = [
  {
    title: '部门名称',
    key: 'name',
  },
  {
    title: '备注',
    key: 'remark',
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'actions',
    width: 180,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <ActionButton onClick={() => handleEdit(row)}>修改</ActionButton>
          <ActionButton v-auth="dept_manage_add" onClick={() => fromAdd(row.id)}>
            新增
          </ActionButton>
          <ActionButton onClick={() => handleDel(row)}>删除</ActionButton>
        </n-flex>
      )
    },
  },
]
function fromAdd(id = null) {
  handleAdd({
    onShow() {
      model.value.parentId = id
    },
  })
}
const { type, model, $form, $table, handleAdd, handleEdit, handleDel, handleSubmit } = useCrud({
  name: '部门',
  initForm: {
    id: null,
    parentId: null,
    name: null,
    remark: null,
  },
  apis: {
    add: deptApi.add,
    edit: deptApi.edit,
    del: ({ id }) => deptApi.del(id),
    view: ({ id }) =>
      deptApi.info(id).then(({ data: { fId, ...other } }) => {
        other['parentId'] = fId
        return other
      }),
  },
  extraChange() {
    getParentOptions()
  },
})

const parentOptions = ref([])
async function getParentOptions() {
  const { data } = await deptApi.tree()
  parentOptions.value = data
}
onBeforeMount(() => {
  getParentOptions()
})
</script>
<style lang="scss" scoped></style>
